package com.osa.birthdaypie;

import java.util.Random;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RadialGradient;

public class Candle {
	private FlameProvider flameProvider;
	private int frame;
	private static final Random RANDOM = new Random();
	private static Bitmap body;
	/**
	 * relative to pie bitmap top left corner
	 */
	private int x;
	/**
	 * relative to pie bitmap top left corner
	 */
	private int y;
	public int getY() {
		return y;
	}

	private int additionalRotation;
	private int additionalRotationCounter;
	private int rotation;
	/**
	 * (x, y) bottom, middle point
	 * @param resources
	 * @param flameProvider
	 * @param x
	 * @param y
	 */
	public Candle(Resources resources, FlameProvider flameProvider, int x, int y) {
		this.flameProvider = flameProvider;
		frame = RANDOM.nextInt(100);
		if (body == null) {
			body = BitmapFactory.decodeResource(resources, R.drawable.candle);
		}
		this.x = x;
		this.y = y;
	}
	
	public void prepareDrawing(int rotation){
		this.rotation = adjustRotation(rotation);
		frame = flameProvider.nextFrame(frame);
	}

	public void draw(Canvas canvas, int pieY) {
		Bitmap flame = flameProvider.getFlame(frame, rotation);
		int flameMiddle = flameProvider.getFlameMiddle(frame, rotation);

		canvas.drawBitmap(body, x - body.getWidth() / 2, pieY + y - body.getHeight(),
				new Paint());
		canvas.drawBitmap(flame, x - flameMiddle, pieY + y - body.getHeight()
				- flame.getHeight(), new Paint());
	}
	
	public int highlightX(){
		final int step = 30;
		return x + step * rotation;
	}
	
	private int adjustRotation(int rotation){
		int res;
		if(additionalRotationCounter > 0){
			additionalRotationCounter--;
		}
		else{
			if(RANDOM.nextDouble() > 0.91){
				additionalRotationCounter = 3;
				additionalRotation = RANDOM.nextBoolean() ? 1 : -1;
			}
			else{
				additionalRotation = 0;
			}
		}
		res = rotation + additionalRotation;
		return res;
	}
}
